<?php


namespace app\controller;


use app\cms\model\shortLinkModel;
use iflow\Response;
use iflow\Router\Controller;
use iflow\Router\implement\Request\GetMapping;

#[Controller('/')]
class index
{

    /**
     * 站点主页
     * @return Response
     */
    #[GetMapping('/')]
    public function home(): Response {
        return view('index');
    }

    /**
     * 短链跳转
     * @param string $short_code
     * @return Response
     */
    #[GetMapping('s/<?:short_code>')]
    public function shortLink(string $short_code): Response
    {
        $url = shortLinkModel::where([
            'short_code' => $short_code
        ]) -> findOrEmpty();
        if ($url -> isEmpty()) return message() -> nodata('404 - NotFound');
        return response() -> setRedirect($url['url']) -> data($url['url']);
    }

    /**
     * 电视直播地址
     * @return Response
     */
    #[GetMapping]
    public function playLiveTv(): Response {
        return view('cms/PlayLiveTv');
    }

    /**
     * 获取视频推流地址
     * @param string $tv_name
     * @param int $size
     * @return Response
     */
    #[GetMapping]
    public function getPlayLiveTvRtmpUrl(string $tv_name = '', int $size = 12): Response {

        $m3u8 = config('live@tvLiveM3U8File', call: function ($file) {
            if (!file_exists($file)) return [];
            $info = file_get_contents($file);
            preg_match_all("#-1 (.*.m3u8)#isU", $info, $context);

            $tvinfo = $context[1] ?? [];

            $m3u8 = [];
            foreach ($tvinfo as $tv) {
                $info = explode("\r\n", $tv);

                $options_tmp = explode(' ', $info[0]);
                $options = [];
                foreach ($options_tmp as $value) {
                    $option = explode('=', $value);
                    if (isset($option[1])) {
                        $options[$option[0]] = trim($option[1], '"');
                    }
                }

                $url =$info[1] ?? '';
                $m3u8[] = [
                    'options' => $options,
                    'url' => $url
                ];
            }
            return $m3u8;
        });

        $tvList = [];
        if ($tv_name === '') {
            array_splice($m3u8, 0, $size);
            return message()->success('OK', $m3u8);
        } else {
            foreach ($m3u8 as $info) {
                if (str_contains($info['options']['tvg-id'], $tv_name)) $tvList[] = $info;
            }
        }
        return message() -> success('OK', $tvList);
    }

    /**
     * 代理获取 m3u8 文件信息
     * @param string $url
     * @return string
     */
    #[GetMapping('proxy_m3u8_server')]
    public function proxyM3u8Server(string $url): string {
        if ($url === '') return "";
        $response = httpRequest($url, headers: [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'
        ]);
        $headers = $response -> response -> getHeaders();

        $TS_URL = '';
        foreach ($headers as $header) {
            $header = explode(": ", $header);
            if (trim($header[0]) === 'Location') $TS_URL = trim($header[1] ?? '');
        }

        $TS_URL = $TS_URL ?: $url;
        $TS = file_get_contents($TS_URL ?: $url);
        preg_match_all("#,(.*.ts)#isU", $TS, $context);
        $match_view  = $context[1];

        foreach ($match_view as $value) {
            $old_value = $value;
            $value = str_replace("\r\n", "", $value);
            $value = str_replace("\r", "", $value);
            $value = str_replace("\n", "", $value);
            $ts  =  "\r\n". request() -> getDomain() ."/proxy_ts_file_server?url=".$TS_URL."/".$value."&ts_url=".$TS_URL;
            $TS = str_replace($old_value, $ts, $TS);
        }
        return $TS;
    }

    /**
     * 获取 ts 文件 内容
     * @param string $url
     * @param string $ts_url
     * @return string|Response
     */
    #[GetMapping('proxy_ts_file_server')]
    public function proxyTSFileServer(string $url, string $ts_url): string|Response {

        $response = file_get_contents($url);
        $ts_urls = parse_url($ts_url);

        // 格式化 m3u8 参数
        $queryUrl = explode('&', $ts_urls['query']);
        $query = [];
        foreach ($queryUrl as $queryValue) {
            $queryValue = explode('=', $queryValue);
            $query[$queryValue[0]] = $queryValue[1];
        }
        $path = str_replace('index.m3u8', '', $ts_urls['path']);
        $ts_url = sprintf("http://%s/%s", $query['ssr_hostlv1'], $path);

        // 获取TS 文件列表
        $tsArr = [];
        preg_match_all("#,(.*.ts)#isU", $response, $tsArr);
        $tsArr = $tsArr[1];
        $content = '';
        $tenantId = request() -> params('tenantId');
        try {
            foreach ($tsArr as $value) {
                $file_url = $ts_url . explode("\r\n", $value)[1];
                if ($tenantId) $file_url .= "&tenantId=$tenantId";
                $content .= file_get_contents($file_url);
            }
            return $content;
        } catch (\Throwable $exception) {
            return $content;
        }
    }
}